package cyou.breathe.blog.user.domain.entity;

import cn.hutool.core.lang.Validator;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.annotation.TableName;
import com.github.houbb.sensitive.annotation.strategy.SensitiveStrategyPhone;
import cyou.breathe.blog.api.user.constant.UserRole;
import cyou.breathe.blog.api.user.constant.UserStateEnum;
import cyou.breathe.blog.datasource.domain.entity.BaseEntity;
import cyou.breathe.blog.user.infrastructure.exception.UserException;
import lombok.Getter;
import lombok.Setter;

import java.util.Date;

import static cyou.breathe.blog.user.infrastructure.exception.UserErrorCode.USER_REGISTER_PARAM_ERROR;

/**
 * @author: breathe
 * @createTime: 2025-08-27
 */
@Setter
@Getter
@TableName("users")
public class User extends BaseEntity {
    /**
     * 昵称
     */
    private String nickName;

    /**
     * 密码
     */
    private String password;

    /**
     * 状态
     */
    private UserStateEnum state;

    /**
     * 邀请码
     */
    private String inviteCode;

    /**
     * 邀请人用户ID
     */
    private String inviterId;

    /**
     * 手机号
     */
    @SensitiveStrategyPhone
    private String telephone;

    /**
     * 邮箱
     */
    private String email;

    /**
     * github平台地址
     */
    private String github;

    /**
     * gitee平台地址
     */
    private String gitee;

    /**
     * 最后登录时间
     */
    private Date lastLoginTime;

    /**
     * 头像地址
     */
    private String profilePhotoUrl;

    /**
     * 用户角色
     */
    private UserRole userRole;

    public User register(String number, String nickName, String password, String inviteCode, String inviterId) {
        if (Validator.isMobile(number)) {
            this.setTelephone(number);
        } else if (Validator.isEmail(number)) {
            this.setEmail(number);
        } else {
            throw new UserException(USER_REGISTER_PARAM_ERROR);
        }
        this.setNickName(nickName);
        this.setPassword(DigestUtil.md5Hex(password));
        this.setState(UserStateEnum.ACTIVE);
        this.setUserRole(UserRole.CUSTOMER);
        this.setInviteCode(inviteCode);
        this.setInviterId(inviterId);
        return this;
    }

    public boolean canModifyInfo() {
        return state == UserStateEnum.ACTIVE;
    }
}
